package com.epam.training.concurrency.first.task1;

import java.util.LinkedList;
import java.util.Queue;

public class Series {

	private final int threadNumber;
	private Queue<NewThread> threads;

	public Series(int threadNumber) {
		this.threadNumber = threadNumber;
		threads = new LinkedList<NewThread>();
	}

	public double calculateSeries(int limitSecond) throws InterruptedException {

		double sum = 0.0;

		int step = limitSecond / threadNumber;

		for (int j = 0; j <= limitSecond; j += step) {
			NewThread thread = new NewThread(j);
			threads.add(thread);
			thread.call();
		}

		for (int i = 0; i < threadNumber; i++) {
			threads.peek().getThread().join();
			sum += threads.poll().getSum();
		}

		return sum;
	}
}
